<template>
  <div class="ingredient-management">

    <div class="ingredient-list">
      <h2>原料列表</h2>
      <div class="scroll-container">
        <ul>
          <!-- 固定标题 -->
          <li class="ingredient-list-header">
            <span class="ingredient-name">原料名称</span>
            <span class="ingredient-supplier">供应商</span>
            <span class="ingredient-purchase-date">采购日期</span>



            <span class="actions">
            <button @click="toggleDeletedIngredients()">
              {{ showingDeletedIngredients ? '回到当前原料' : '查看历史原料' }}
            </button>

            </span>
          </li>
          <!-- 列表项 -->
          <li v-for="ingredient in ingredients" :key="ingredient.ingredient_id">
            <span class="ingredient-name">{{ ingredient.name }}</span>
            <span class="ingredient-supplier">{{ ingredient.supplier }}</span>
            <span class="ingredient-purchase-date">{{ ingredient.purchase_date }}</span>
            <div class="actions">
              <button v-if="!showingDeletedIngredients" @click="editIngredient(ingredient)">编辑</button>
              <button v-if="!showingDeletedIngredients" @click="deleteIngredient(ingredient)">删除</button>
              <button v-if="showingDeletedIngredients" @click="restoreIngredient(ingredient)">恢复</button>
            </div>
          </li>
        </ul>
      </div>
    </div>


    <div class="ingredient-forms">
    <!-- 添加/编辑原料表单 -->
    <div class="ingredient-form">
      <h2>添加新原料</h2>
      <form @submit.prevent="submitIngredient">
        <input v-model="form.name" type="text" placeholder="原料名称" />
        <input v-model="form.supplier" type="text" placeholder="供应商" />
        <input v-model="form.purchase_date" type="date" placeholder="采购日期" />

        <button type="submit">添加</button>
      </form>

    </div>
    <div class="ingredient-form" v-if="editingIngredient">
      <h2>编辑原料</h2>
      <form @submit.prevent="submitIngredient">
        <input v-model="editForm.name" type="text" placeholder="原料名称" />
        <input v-model="editForm.supplier" type="text" placeholder="供应商" />
        <input v-model="editForm.purchase_date" type="date" placeholder="采购日期" />

        <button type="submit">更新</button>
        <button type="button" @click="resetForm">取消编辑</button>
      </form>
    </div>
    </div>
  </div>
</template>

<script>
import { getAllIngredients, getAllDeletedIngredients, addNewIngredient, updateIngredient } from '@/api/ingredients';

export default {
  data() {
    return {
      ingredients: [],
      form: { name: '', supplier: '', purchase_date: '', is_deleted: 'no' },
      editForm: { name: '', supplier: '', purchase_date: '', is_deleted: 'no' },
      editingIngredient: null,
      showingDeletedIngredients: false,

    };
  },

  methods: {

    toggleDeletedIngredients() {
      this.showingDeletedIngredients = !this.showingDeletedIngredients;
      this.fetchIngredients();
    },
    async fetchIngredients() {
      try {
        const response = this.showingDeletedIngredients ? await getAllDeletedIngredients() : await getAllIngredients();
        this.ingredients = response.data;
      } catch (error) {
        console.error(error);
      }
    },
    async restoreIngredient(ingredient) {
      try {
        ingredient.is_deleted = 'no';
        await updateIngredient(ingredient.ingredient_id, ingredient);
        await this.fetchIngredients(); // 更新原料列表
      } catch (error) {
        console.error(error);
      }
    },

    editIngredient(ingredient) {
      this.editingIngredient = ingredient;
      this.editForm = { ...ingredient };
    },


    async deleteIngredient(ingredient) {
      const confirmation = confirm('确定要删除这个原料吗？');
      if (!confirmation) {
        return;
      }
      this.loading = true;
      try {
        ingredient.is_deleted = 'yes';
        await updateIngredient(ingredient.ingredient_id, ingredient);
        await this.fetchIngredients(); // 重新获取原料列表
      } catch (error) {
        console.error(error);
      }
    },

    async submitIngredient() {
      // 如果没有选择日期，则设置为今天的日期
      if (!this.form.purchase_date && !this.editingIngredient) {
        let today = new Date();
        let formattedDate = today.getFullYear() + '-' +
            (today.getMonth() + 1).toString().padStart(2, '0') + '-' +
            today.getDate().toString().padStart(2, '0');
        this.form.purchase_date = formattedDate;
      }

      // 准备提交的原料数据
      let ingredientData = {
        name: this.editingIngredient ? this.editForm.name : this.form.name,
        supplier: this.editingIngredient ? this.editForm.supplier : this.form.supplier,
        purchase_date: this.editingIngredient ? this.editForm.purchase_date : this.form.purchase_date,
        is_deleted: this.editingIngredient ? this.editForm.is_deleted : this.form.is_deleted
      };

      try {
        let response;

        // 判断是添加还是编辑原料
        if (this.editingIngredient) {
          // 编辑模式
          response = await updateIngredient(this.editingIngredient.ingredient_id, ingredientData);
        } else {
          // 添加模式
          response = await addNewIngredient(ingredientData);
        }

        this.resetForm(); // 重置表单
        await this.fetchIngredients(); // 重新获取原料列表

        // 根据响应显示消息
        if (response && response.data) {
          // 假设后端返回的成功消息存储在response.data.message中
          alert(response.data.message || '原料更新成功');
        } else {
          // 若没有明确的消息，则失败
          console.log('TEST11')
          alert('原料更新失败');
        }
      } catch (error) {
        // 处理错误情况
        if (error.response && error.response.data) {
          // 假设后端返回的错误消息存储在error.response.data.message中
          alert(error.response.data.message || '原料更新失败');
        } else {
          // 若没有明确的错误消息，则显示默认错误消息
          console.log('TEST22')
          error.response
          error.message
          alert('原料更新失败');
        }
        console.log('TEST3333')
        error.response
        error.message
        console.error('原料更新失败', error);
      }
    },

    resetForm() {
      this.form = { name: '', supplier: '', purchase_date: '', is_deleted: 'no' };
      this.editingIngredient = null;
    }
  },
  mounted() {
    this.fetchIngredients();
  },
};
</script>

<style scoped>
.ingredient-management {
  max-height: 85vh;

  font-family: 'Arial', sans-serif;
  display: flex;
  gap: 20px;
  margin: 0 auto;
  max-width: 1200px;
  padding: 20px;
}

.ingredient-management h2 {
  color: #333;
  text-align: center;
}


.ingredient-list,
.ingredient-forms {

  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 15px;
  flex: 1;
}

.ingredient-form {
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 8px;
  margin-bottom: 20px;

  padding: 15px;
  flex: 1;
}

.ingredient-list {
  overflow-y: auto;
}

.scroll-container {
  max-height: 82vh; /* 或您希望的最大高度 */
  overflow-y: auto;
}

.ingredient-list-header {

  position: sticky;
  top: 0;
  background-color: white;
  z-index: 100;
}

/* 以下是额外的样式，用于确保布局整洁 */
.ingredient-list-header span, .ingredient-list li span {
  display: inline-block;
  /* 根据需要调整宽度 */
  width: 120px;
}



.ingredient-list ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.ingredient-list li {
  background-color: #fff;
  border: 1px solid #eee;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
  padding: 1px
}

.ingredient-list .actions {
  //display: flex;
  gap: 10px;
  display: inline-block;
  /* 根据需要调整宽度 */
  width: 100px;
  font-weight: bold;

}

.ingredient-list .ingredient-name,
.ingredient-list .ingredient-supplier,
.ingredient-list .ingredient-purchase-date {
  font-weight: bold;
  color: #333;
  text-align: center;
  display: block;
  width: calc(100% / 4 - 10px);

}

.ingredient-list button {
  background-color: #93bdd8;
  border: none;
  border-radius: 4px;
  color: white;
  cursor: pointer;
  padding: 10px 15px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 14px;
  margin-top: 5px;
  margin-bottom: 5px;
  padding: 5px;
}

.ingredient-list .actions button {
  margin-right: 2px;
}

.ingredient-list .actions button:last-child {
  margin-right: 0;
}

.ingredient-list button:hover {
  background-color: #A4D3F1;
}

.ingredient-form input[type="text"],
.ingredient-form input[type="date"] {
  display: block;
  width: 100%;
  padding: 10px;
  margin: 10px auto;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-sizing: border-box;
  font-size: 16px;
}

.ingredient-form button {
  display: block;
  width: 100%;
  background-color: #93bdd8;
  color: white;
  padding: 14px 20px;
  margin: 10px 0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 18px;
  font-weight: bold;
}

.ingredient-form button:hover {
  background-color: #A4D3F1;
}

.ingredient-forms > .ingredient-form:last-child {
  margin-bottom: 0;
}
</style>

